#include "dataexporter.h"
#include "qsqlerror.h"
#include "qsqlrecord.h"

#include <QSqlQuery>
#include <QStringList>

QString DataExporter::m_lastError;

DataExporter::DataExporter(QObject *parent)
    : QObject{parent}
{}

bool DataExporter::exportToCsv(QSqlQueryModel *model, const QString &fileName, const QString &separator, const QString &textEncoding)
{
    if (!model || model->rowCount() == 0) {
        m_lastError = QObject::tr("模型数据为空或无效");
        return false;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        m_lastError = QObject::tr("文件创建失败: %1").arg(file.errorString());
        return false;
    }

    QTextStream stream(&file);
    stream.setCodec(textEncoding.toUtf8());  // 设置编码格式

    // 写入表头
    for (int col = 0; col < model->columnCount(); ++col) {
        QString header = model->headerData(col, Qt::Horizontal).toString();
        stream << formatCsvData(header) << separator;
    }
    stream << "\n";

    // 遍历数据行
    for (int row = 0; row < model->rowCount(); ++row) {
        for (int col = 0; col < model->columnCount(); ++col) {
            QModelIndex index = model->index(row, col);
            QVariant data = model->data(index);
            stream << formatCsvData(data) << separator;
        }
        stream << "\n";
    }

    file.close();
    return true;
}


QString DataExporter::formatCsvData(const QVariant &data, const QString &textDelimiter)
{
    QString str = data.toString().replace("\"", "\"\"");  // 转义双引号
    if (str.contains(QRegExp("[,;\t\n\r]"))) {  // 包含特殊字符时添加定界符
        return textDelimiter + str + textDelimiter;
    }
    return str;
}
